package com.itheima.search.service;

import com.alibaba.fastjson.JSON;
import com.itheima.item.client.ItemClient;
import com.itheima.item.pojo.GoodInfo;
import com.itheima.search.constant.ParamConstant;
import com.itheima.search.pojo.Result;
import com.itheima.search.utils.KibanaUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;


    @RabbitListener(queues = "updateMsg")
    public void update(Long id){
        GoodInfo goodInfo = itemClient.findGoodsById(id);
        if (goodInfo==null){
        KibanaUtil.deleteDocumentTest("goods",String.valueOf(id));
        }else {
        KibanaUtil.addDocumentTest("goods",String.valueOf(id),goodInfo);
        }
    }


    public void export() {
        if (KibanaUtil.isIndexExits("goods")) {
            KibanaUtil.deleteIndex("goods");
        }
        KibanaUtil.createIndexAndMapping("goods","{\n" +
                "  \"mappings\" : {\n" +
                "      \"properties\" : {\n" +
                "        \"name\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\":\"ik_max_word\"\n" +
                "        },\n" +
                "        \"image\" : {\n" +
                "          \"type\" : \"keyword\",\n" +
                "          \"index\": false\n" +
                "        },\n" +
                "        \"updateTime\" : {\n" +
                "          \"type\" : \"date\"\n" +
                "        }\n" +
                "        \n" +
                "      }\n" +
                "    }\n" +
                "  \n" +
                "}");
        int count = itemClient.count();
        int times = count%10000==0? count/10000:(count/10000)+1;
        for (int i = 0; i < times; i++) {
            List<GoodInfo> list = itemClient.findByPage(i*10000, 10000);
            System.out.println(list.size());
            for (GoodInfo goodInfo : list) {
                KibanaUtil.bulkAdd("goods",goodInfo.getId().toString(), JSON.toJSONString(goodInfo));
            }
            KibanaUtil.bulkExport();
        }
    }


    public Result search(Map param) {
        if (param.get("keyword")==null&&param.get("keyword")!=""){
            return null;
        }
        Integer pageSize =(Integer) param.get("pageSize");
        Integer pageNum =(Integer) param.get("pageNum");
        SearchSourceBuilder builder = new SearchSourceBuilder();
       /* builder.query(QueryBuilders.matchQuery("name", (String)param.get("keyword"))).from(pageSize*(pageNum-1)).size(pageSize)
                .highlighter(new HighlightBuilder().field("name").preTags("<span style=\"color: red\">").postTags("</span>"));*/
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        builder.query(boolQueryBuilder.must(QueryBuilders.matchQuery("name",(String)param.get("keyword"))));
        if (param.get("range")!=null&&param.get("range")!=""){
            String range =(String) param.get("range");
            int i = range.indexOf("-");
            int gte = Integer.valueOf(range.substring(0, i));
            int lte = Integer.valueOf(range.substring(i + 1));
            boolQueryBuilder.must(QueryBuilders.rangeQuery("price").gte(gte).lte(lte));
        }
        builder.from(pageSize*(pageNum-1)).size(pageSize).highlighter(new HighlightBuilder().field("name").preTags("<span style=\"color: red\">").postTags("</span>"));


        SearchRequest searchRequest = new SearchRequest("goods");

        switch((String)param.get("key")){
            case ParamConstant.PRICE :
                //语句
                builder.sort("price", SortOrder.ASC);
                System.out.println("11111111111");
                break; //可选
            case ParamConstant.ARRIVAL:
                //语句
                builder.sort("updateTime", SortOrder.ASC).sort("id",SortOrder.ASC);
                System.out.println("22222222222");
                break; //可选
            //你可以有任意数量的case语句
            case ParamConstant.SALES:
                builder.sort("saleNum", SortOrder.DESC);
                System.out.println("333333333");
                break;
            default : //可选
                //语句
                break;
        }
        searchRequest.source(builder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        SearchHits searchHits = response.getHits();
        System.out.println("共查到" + searchHits.getTotalHits().value + "条");

        SearchHit[] hits = searchHits.getHits();
        List<GoodInfo> list = new ArrayList<>();
        for (SearchHit hit : hits) {

            GoodInfo goodInfo = JSON.parseObject(hit.getSourceAsString(), GoodInfo.class);
            if (hit.getHighlightFields() != null && hit.getHighlightFields().size() != 0)
                goodInfo.setName(StringUtils.join(hit.getHighlightFields().get("name").getFragments()));
            list.add(goodInfo);
            System.out.println(goodInfo);
        }
        long total = searchHits.getTotalHits().value;
        Result result = new Result();
        result.setObj(list);
        result.setPages((int)(total%pageSize==0?total/pageSize:total/pageSize+1));
        result.setCount((int) searchHits.getTotalHits().value);
        return result;
    }
}